<?php namespace App\Admin\Enterprise\Personnel;

//基础条件
use App\Core\Repository\Criterias\PaginateCriteria;
use App\Core\Repository\Criterias\SortCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputCriteria;
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputTimeRangeCriteria;

use Input;
use DB;
require_once app_path().'/Library/excel/PHPExcel.php';
use App\Admin\Enterprise\Enterprise\Repository as EnterpriseRepository;


trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\All;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    //操作日志
    use \App\Admin\Base\LogService;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
    }
	
    //列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputKeywordsCriteria('name,phone'),
            new InputTimeRangeCriteria('created_at'),
            new InputCriteria('gender'),
            new Criterias\MatchCabinet()
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $conditions[] = new SortCriteria('id', 'DESC');
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->all();
        $data->load('enterprise');
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }


    public function importCheck(){
        $enterpriseId = Input::get('enterpriseId');
        if(!$enterpriseId){
            return $this->inputError('参数有误');
        }

        try{
            $file = Input::file('file');
        } catch (\Exception $exc){
            return $this->inputError($exc->getMessage());
        }
        if(empty($file)){
            return $this->inputError('文件不存在');
        }
        $filePath = $file->getPathName();
        if(!file_exists($filePath)){
            return $this->inputError('文件不存在');
        }
        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                return $this->inputError('文件格式不支持');
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        $dataArray = $PHPExcel->getSheet(0)->toArray();

        $data = DB::table('enterprise_user')
//            ->where('enterprise_id','=',$enterpriseId)
            ->where('is_delete','=','0')
            ->get();
        $arrData = array();
        foreach ($data as $dataIndex){
            $arrData[] = $dataIndex->phone;
        }

        $indexArr = array();
        foreach ($dataArray as $key1 =>$row){
            if($key1 ==0 ){
                foreach ($row as $key2 =>$col){
                    if('姓名' == $col){
                        $indexArr['姓名'] = $key2;
                    }
                    if('企业' == $col){
                        $indexArr['企业'] = $key2;
                    }
                    if('性别' == $col){
                        $indexArr['性别'] = $key2;
                    }
                    if('手机号' == $col){
                        $indexArr['手机号'] = $key2;
                    }
                }
                continue;
            }
            if($row[$indexArr['姓名']] && $row[$indexArr['手机号']]){
                $gender = 0;
                if(trim($row[$indexArr['性别']]) == '男'){
                    $gender= 1;
                }else  if(trim($row[$indexArr['性别']]) == '女'){
                    $gender= 2;
                }

                if(in_array($row[$indexArr['手机号']],$arrData)){
                    continue;
                }

                //验证手机号
                if(preg_match("/^1[34578]\d{9}$/", $row[$indexArr['手机号']])){

                    $is_bind = 0;
                    //判断user表 用户是否已经存在
                    $user = DB::table('user')
                        ->where('phone','=',$row[$indexArr['手机号']])
                        ->where('is_delete','=','0')
                        ->where('login_status','=','1')
                        ->first();

                    if($user){
                        //$user->enterprise_id = $enterpriseId;
                        //$user->save();
                        DB::table('user')->where('phone','=',$row[$indexArr['手机号']])
                            ->where('is_delete','=','0')
                            ->where('login_status','=','1')->update([
                                'enterprise_id'=>$enterpriseId
                            ]);
                        $is_bind = 1;
                    }

                    //插入数据库
                    DB::table('enterprise_user')->insertGetId([
                        'name'=>$row[$indexArr['姓名']],
                        'phone'=>$row[$indexArr['手机号']],
                        'enterprise_id'=>$enterpriseId,
                        'gender'=>$gender,
                        'is_bind'=>$is_bind,
                        'created_at'=>time(),
                        'updated_at'=>time()
                    ]);

                }
            }
        }
        return $this->success();
    }

}